﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using OpenIddict.EntityFrameworkCore.Models;
using SageKing.Core.Extensions;
using SageKing.Database.Contracts;
using SageKing.Database.Service;
using SageKing.OpenIddict.UI.Api;

namespace SageKing.OpenIddict.Services.BaseService;

public class ApplicationApiBaseService
    (ApplicationApiHttpClient applicationApiService) : BaseService<ApplicationViewModel, string>, IEntityPage<OpenIddictEntityFrameworkCoreApplication, ApplicationViewModel>
{

    public override async Task<ApplicationViewModel> GetDetail(string id)
    {
        var getEntity = await applicationApiService.GetAsync(id);
        return getEntity;
    }

    public override async Task<ApplicationViewModel> AddReturnEntityAsync(ApplicationViewModel entity)
    {
        var result = await applicationApiService.CreateAsync(entity);
        var getEntity = await applicationApiService.GetAsync(result);
        return getEntity;
    }

    public override async Task<int> Update(ApplicationViewModel entity)
    {
        if (entity.ClientSecret.IsNullOrEmpty())
        {
            var getEntity = await applicationApiService.GetAsync(entity.Id);
            entity.ClientSecret = getEntity.ClientSecret;
        }
        await applicationApiService.UpdateAsync(entity);
        return 1;
    }

    public override async Task<int> UpdateWithOptLock(ApplicationViewModel entity)
    {
        if (entity.ClientSecret.IsNullOrEmpty())
        {
            var getEntity = await applicationApiService.GetAsync(entity.Id);
            entity.ClientSecret = getEntity.ClientSecret;
        }
        await applicationApiService.UpdateAsync(entity);
        return 1;
    }

    public override async Task<bool> Delete(string id)
    {
        await applicationApiService.DeleteAsync(id);
        return true;
    }

    #region page
    public async Task<PageBase<ApplicationViewModel>> GetPage(PageBaseInput page, Expression<Func<OpenIddictEntityFrameworkCoreApplication, object>> orderby, bool orderByAsc = true)
    {
        return await applicationApiService.GetPage(page, orderby, orderByAsc);
    }

    public Task<PageBase<ApplicationViewModel>> GetPage(PageBaseInput page, List<(bool, Expression<Func<OpenIddictEntityFrameworkCoreApplication, bool>>)> whereIf, Expression<Func<OpenIddictEntityFrameworkCoreApplication, object>> orderby, bool orderByAsc = true)
    {
        return applicationApiService.GetPage(page, whereIf, orderby, orderByAsc);
    }

    #endregion
}
